/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2019/3/24 12:12
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class BlockedQueue<T> {

    List<T> data = new ArrayList<T>(1);

    // 互斥锁
    final Lock lock = new ReentrantLock();
    // 条件变量：队列不满
    final Condition notFull = lock.newCondition();
    // 条件变量：队列不空
    final Condition notEmpty = lock.newCondition();

    // 入队
    void enq(T t) throws InterruptedException {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"->in....");
            while (data.size() > 0) {
                System.out.println(Thread.currentThread().getName()+"->wait....");
                notFull.await();
                System.out.println(Thread.currentThread().getName()+"->释放锁....");
            }
            System.out.println(Thread.currentThread().getName()+"->continue....");
            Thread.sleep(1000);
            data.add(t);
            notEmpty.signal();
        } finally {
            System.out.println(data);
            lock.unlock();
        }
    }

    // 出队
    void dnq(T t) throws InterruptedException {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"->in....");
            while (data.size() == 0) {
                System.out.println(Thread.currentThread().getName()+"->wait....");
                notEmpty.await();
                System.out.println(Thread.currentThread().getName()+"->释放锁....");
            }
            System.out.println(Thread.currentThread().getName()+"->continue....");
            Thread.sleep(1000);
            data.remove(t);
            notFull.signal();
        } finally {
            System.out.println(data);
            lock.unlock();
        }
    }
}
